package wml.clipstore.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import wml.clipstore.base.Entity;

public class EntityUtils {

	public static String getStringValue(Entity entity, Field f) {
		String sValue = "";
		try {
			Object value = getValue(entity, f);
			if (isSubClass(f.getType(), Collection.class)) {
				sValue = " \"" + value.hashCode() + "@"
						+ value.getClass().getName() + "\"";
			} else {
				sValue = " \"" + value + "\"";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sValue;
	}

	public static Object getValue(Entity entity, Field f) {
		try {
			f.setAccessible(true);
			Object value = f.get(entity);
			return value;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static List<Field> getFields(Class<? extends Entity> clazz) {
		List<Field> fields = new ArrayList<Field>();
		List<Class<? extends Entity>> classes = getSuperClasses(clazz);
		for (Class<? extends Entity> c : classes) {
			for (Field field : c.getDeclaredFields()) {
				fields.add(field);
			}
		}
		return fields;
	}

	@SuppressWarnings("unchecked")
	private static List<Class<? extends Entity>> getSuperClasses(
			Class<? extends Entity> clazz) {
		List<Class<? extends Entity>> classes = new ArrayList<Class<? extends Entity>>();
		Class<? extends Entity> tc = clazz;
		while (!tc.equals(Entity.class)) {
			classes.add(tc);
			tc = (Class<? extends Entity>) tc.getSuperclass();
		}
		return classes;
	}

	public static boolean isSubClass(Class<?> sub, Class<?> sup) {
		try {
			sub.asSubclass(sup);
		} catch (ClassCastException e) {
			return false;
		}
		return true;
	}
}
